package com.cetcs.kmga.dataManager.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * Ehcache工具类
 *
 * @author xutao
 * @version V1.0 创建时间：2017-10-17 9:41
 *          Copyright 2017 by CETC
 */
public class EhcacheUtil {
    private static final String path = "conf/ehcache.xml";

    private Cache cache = null;

    public EhcacheUtil(String cacheName) {
        init(cacheName);
    }

    private void init(String cacheName) {
        InputStream inputStream = this.getClass( ).getClassLoader( ).getResourceAsStream(path);
        CacheManager manager = CacheManager.newInstance(inputStream);
        cache = manager.getCache(cacheName);
    }

    public void put(Element element) {
        //Element element = new Element(key, value);
        if (cache != null) {
            cache.put(element);
        }
    }

    public Element get(String key) {
        if (cache != null) {
            Element element = cache.get(key);
            return element;
        }
        return null;

    }

    public Map<Object, Element> getAllElements() {
        if (cache != null) {
            try {
                List keyList = cache.getKeys( );
                if (keyList != null) {
                    Map<Object, Element> elementMap = cache.getAll(keyList);
                    return elementMap;
                }
            } catch (Exception ex) {
                ex.printStackTrace( );
            }
        }
        return null;
    }

    public void remove(String cacheName) {
        cache.remove(cacheName);
    }
}
